package com.example.algorithm.test;

import org.junit.Test;

import java.util.Arrays;
import java.util.stream.IntStream;

/**
 * 6.寻找数组的中心下标
 * @auther lijiewei
 * @date 2024-03-11 19:43
 */
public class ArrayMiddleIndex {

    /** 方案1. */
    private int programme1(int[] nums) {
        int sum = IntStream.of(nums).sum();
        if (sum == 0) {
            return -1;
        }
        int total = 0;
        for (int i = 0; i < nums.length; i++) {
            total += nums[i];
            if (total == sum) {
                return i;
            }
            sum -= nums[i];
        }
        return -1;
    }

    @Test
    public void programme1Test() throws Exception{
        System.out.println(programme1(new int[]{1, 7, 3, 6, 5, 6}));
    }


    /** 方案2. */
    private int programme2(int[] nums) {
        int sum = IntStream.of(nums).sum();
        if (sum == 0) {
            return -1;
        }
        int total = 0;
        for (int i = 0; i < nums.length; i++) {
            if (2 * total + nums[i] == sum) {
                return i;
            }
            total += nums[i];
        }
        return -1;
    }

    @Test
    public void programme2Test() throws Exception{
        System.out.println(programme2(new int[]{1, 7, 3, 6, 5, 6}));
    }
}
